from sqlalchemy import asc
from src.common.logger import getLogger

logger = getLogger()

def load_memory_details(args):
    from ..model.memory_detail import MemoryDetail
    source_id = args.get("source_id")

    query = MemoryDetail.query

    if source_id:
        query = query.filter(MemoryDetail.source_id == source_id)

    records = query.order_by(asc(MemoryDetail.create_time)).all()

    list = []
    for record in records:
        item = record.to_dict()
        if item["create_time"]:
            item["create_time"] = item["create_time"].strftime('%Y-%m-%d %H:%M:%S')
        list.append(item)
    return list

def insert_memory_detail(memory_detail):
    from ... import db
    db.session.add(memory_detail)
    db.session.commit()

def delete_memory_detail(id):
    from ... import db
    from ..model.memory_detail import MemoryDetail

    list = MemoryDetail.query.filter(MemoryDetail.source_id == id).all()
    logger.info(f"delete_memory_detail list len: {len(list)}")
    for detail in list:
        db.session.delete(detail)
    db.session.commit()
